<template>
  <div class="scanner-input-wrap" v-show="show">
    <div>扫描枪测试</div>
    <div>测试结果: {{ this.scannerInput }}</div>
  </div>
</template>

<script>

export default {
  props: {
    show: {
      type: Boolean,
      default() {
        return true;
      },
    }
  },
  data() {
    return {
      scannerInput: '',
      scannerInputTemp: [],
      lastTimestamp: null,
      // 区分扫码枪和正常键盘输入的临界值
      intervalTimestamp: 160,
    }
  },
  created() {

  },
  mounted() {
    this.run();
  },
  methods: {
    async run() {
      // 监听键盘输入，以每个键输入的间隔区分
      document.addEventListener('keyup', (event) => {
        const timestamp = new Date().getTime();

        if (this.lastTimestamp === null) {
          this.lastTimestamp = timestamp;
        }

        if (timestamp - this.lastTimestamp >= 320) {
          this.scannerInputTemp = [this.formatKeyData(event)];
        } else {
          if (event.key === 'Enter') {
            this.scannerInput = this.join();
            this.$emit('onScannerInput', this.scannerInput);
            this.scannerInputTemp = [];
          } else {
            this.scannerInputTemp.push(this.formatKeyData(event));
          }
        }
        this.lastTimestamp = timestamp;
      });
    },

    formatKeyData(event) {
      return {
        key: event.key,
        code: event.code,
      }
    },

    join() {
      // 将 shift 键的对应关系列出来
      const keyboardShiftCharacters = {
        '`': '~',
        '1': '!',
        '2': '@',
        '3': '#',
        '4': '$',
        '5': '%',
        '6': '^',
        '7': '&',
        '8': '*',
        '9': '(',
        '0': ')',
        '-': '_',
        '=': '+',
        '[': '{',
        ']': '}',
        '\\': '|',
        ';': ':',
        "'": '"',
        ',': '<',
        '.': '>',
        '/': '?',
        'a': 'A',
        'b': 'B',
        'c': 'C',
        'd': 'D',
        'e': 'E',
        'f': 'F',
        'g': 'G',
        'h': 'H',
        'i': 'I',
        'j': 'J',
        'k': 'K',
        'l': 'L',
        'm': 'M',
        'n': 'N',
        'o': 'O',
        'p': 'P',
        'q': 'Q',
        'r': 'R',
        's': 'S',
        't': 'T',
        'u': 'U',
        'v': 'V',
        'w': 'W',
        'x': 'X',
        'y': 'Y',
        'z': 'Z'
      };

      let str = '';
      let isShift = false;
      this.scannerInputTemp.forEach(v => {

        if (v.key === 'Shift') {
          isShift = true;
        } else {
          const char = isShift ? (keyboardShiftCharacters[v.key] ? keyboardShiftCharacters[v.key] : v.key) : v.key;
          if (isShift) {
            isShift = false;
          }

          str += char;
        }
      })
      return str;
    },

  }
}
</script>

<style scoped lang="less">
.scanner-input-wrap{

}
</style>
